<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="数据源管理">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
        :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" id="moss-basicTable" :bordered="false">
        <template #tableTitle>
          <n-button type="primary" :on-click="handleEdit.bind(null, {}, true)">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加数据源
          </n-button>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle" style="width: 720px;">
      <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="数据源类型" path="dataSourceType">
            <n-select v-model:value="fromValues.dataSourceType" placeholder="请选择数据源类型" :options="dataSourceType" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="数据库地址" path="databaseHost">
            <n-input maxlength="32" show-count placeholder="请输入数据库地址" v-model:value="fromValues.databaseHost" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="数据库端口" path="databasePort">
            <n-input-number style="width: 100%;" placeholder="请输入数据库端口" v-model:value="fromValues.databasePort" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="数据库用户名" path="databaseUserName">
            <n-input maxlength="32" show-count placeholder="请输入数据库用户名" v-model:value="fromValues.databaseUserName" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="数据库密码" path="databasePassword">
            <n-input maxlength="32" show-count placeholder="请输入数据库密码" v-model:value="fromValues.databasePassword" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="数据库名称" path="databaseName">
            <n-input maxlength="32" show-count placeholder="请输入数据库名称" v-model:value="fromValues.databaseName" />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="数据库完整链接地址" path="fullConnection">
            <n-input maxlength="300" show-count type="textarea" :autosize="{
              minRows: 3,
              maxRows: 5
            }" v-model:value="fromValues.fullConnection" filterable
              placeholder="请输入数据库完整链接地址(如:jdbc:mysql://192.168.1.57:3306/moss-cloud-plugins?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false)" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseModel">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>

  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h, onMounted, unref } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import { dataSourcePage, saveDataSourceConf, updateDataSourceConf, removeDataSourceConf } from '@/api/plugins/dataSource';
import { dictGroup } from '@/api/system/dict';
import { columns } from './columns';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
const message = useMessage();
const actionRef = ref();
const showModal = ref(false);
const formBtnLoading = ref(false);
const editTitle = ref('');
const isAdd = ref(true);
const formRef: any = ref(null);
const dialog = useDialog();
const dataSourceType = ref<[]>([]);
const defaultValueRef = () => ({
  id: null,
  /**数据源类型（基础服字典表）*/
  dataSourceType: '',
  /**数据库名称(链接字符串)*/
  databaseName: '',
  /**完整连接地址*/
  fullConnection: '',
  /**数据库地址*/
  databaseHost: '',
  /**数据库端口*/
  databasePort: 3306,
  /**数据库用户名*/
  databaseUserName: '',
  /**数据库密码*/
  databasePassword: '',
});
let fromValues = reactive(defaultValueRef());
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  {
    field: 'databaseHost',
    component: 'NInput',
    label: '数据库地址',
    componentProps: {
      placeholder: '请输入数据库地址',
    },
  },
  {
    field: 'dataSourceType',
    component: 'NSelect',
    label: '数据源类型',
    componentProps: {
      placeholder: '请选择数据源类型',
      options: dataSourceType,
    },
  },
];
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 120,
  schemas,
});
const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
    });
  },
});

function createActions(record) {
  return [
    {
      label: '删除',
      type: 'error',
      // 配置 color 会覆盖 type
      color: 'red',
      icon: DeleteOutlined,
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      //auth: ['basic_list'],
    },
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record, false),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
  ];
}
const rules: FormRules = {
  databaseName: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入数据库名称',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  fullConnection: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入完整连接地址',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  databaseHost: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入数据库地址',
  },
  databasePort: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入数据库端口',
  },
  databaseUserName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入数据库用户名',
  },
  databasePassword: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入数据库密码',
  },
  dataSourceType: {
    type: 'string',
    required: true,
    trigger: ['blur', 'select'],
    message: '请选择数据源类型',
  },
};
const loadDataTable = async (res: any) => {
  return await dataSourcePage({ ...getFieldsValue(), ...res });
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}
/**
 * 查询
 */
function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
function resetFrom() {
  fromValues = Object.assign(unref(fromValues), defaultValueRef());
}
/**
 * 新增编辑提交数据
 * @param e 
 */
function confirmForm(e: any) {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      const data = isAdd.value ? await saveDataSourceConf(fromValues) : await updateDataSourceConf(fromValues);
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
        formBtnLoading.value = false;
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showModal.value = false;
        formBtnLoading.value = false;
        resetFrom();
        reloadTable();
      }
    } else {
      message.error('请填写完整信息');
    }
  });
}
/**
 * 新增编辑model
 * @param record 
 * @param addStatus 
 */
function handleEdit(record: Recordable, addStatus: boolean) {
  showModal.value = true;
  isAdd.value = addStatus;
  if (addStatus) {
    editTitle.value = `新增数据源`;
  } else {
    editTitle.value = `编辑 ${record.databaseName}`;
    fromValues = Object.assign(fromValues, record);
  }
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
  resetFrom();
  showModal.value = false;
}
/**
 * 删除确认
 * @param record 
 */
function handleDelete(record: Recordable) {
  dialog.warning({
    title: '警告',
    content: `确定删除${record.databaseName}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await removeDataSourceConf({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        reloadTable();
      }
    },
  })
}
/**
 * 数据源类型
 */
const getDataSourceType = async () => {
  const data = await dictGroup({ dictGroup: 'data_source_type' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  dataSourceType.value = arry;
}
/**
 * 初始化数据
 */
onMounted(async () => {
  getDataSourceType();
});
</script>

<style lang="less" scoped></style>
